import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store";
import i18n from '@/i18n';
import routers from "./routerTree.js"
//引入nprogress
import NProgress from "nprogress"; // 进度条
import "nprogress/nprogress.css"; //这个样式必须引入
Vue.use(VueRouter);
let tempRoute = addDynamicMenuRoutes(routers)

store.commit('setRouterTree',routers)
const routes = [
  {
    path: "/login",
    name: "登录",
    component: () => import("@/views/login.vue"),
    meta:{
      index: '0'
    }
  },
  {
    path: "*",
    name: "page not fond",
    component: () => import("@/views/404.vue")
  },
  {
    path: "/",
    name: "内部视口",
    redirect: "/home",
    component: () => import("@/views/index.vue"),
    meta:{
    },
    children: tempRoute
  }
];
const router = new VueRouter({
  routes
});
var messageInstance = null;
router.beforeEach((to, from, next) => {
  NProgress.start();
  // 去登录页，下面不需要执行
  if (to.path === "/login") {
    NProgress.done();
    return next();
  }
  if (!store.state.userInfo.username) {
    NProgress.done();
    //没有登录，去跳转登录页
    if (to.path === "/login") {
      return next();
    } else {
      if (messageInstance) {
        messageInstance.close();
      }
      messageInstance = Vue.prototype.$message.error(i18n.t('SYS.shouldLogin'));
      return next({ path: "/login" });
    }
  } else {
    next();
  }
});
router.afterEach(() => {
  NProgress.done();
});
store.commit('removeState')
window.onbeforeunload=function (e){
  store.commit('saveState')
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicMenuRoutes (menuList = [], routes = []){
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
      continue
    }
    // 组装路由
    var route = {
      path: menuList[i].path,
      component: menuList[i].component,
      name: menuList[i].name,
      meta: menuList[i].meta
    }
    if ( route.path ) {
      routes.push(route)
    }
    if (temp.length >= 1) {
      return addDynamicMenuRoutes(temp, routes)
    }
  }
  return routes
}

export default router;
